<?php

/**
 * Application registry
 * 
 * Stores the variables and settings used accross the application
 * 
 * Applied patterns:
 *   * Singleton
 */
class AppRegistry {
	
	protected static $instance = null;
	
	protected $variables = array();
	protected $arguments = array();
	
	public function getInstance() {
		if(self::$instance == null)
			self::$instance = new AppRegistry();
		return self::$instance;
	}
	
	/**
	 * Creates a new AppRegistry instance and loads up the command line arguments
	 *
	 */
	protected function __construct() {
		$this->arguments = $GLOBALS["argv"];
	}
	
	
	/**
	 * Returns the target directory
	 *
	 * @return String The target directory as supplied from the command line
	 * 
	 */
	public function getTargetDirectory() {
		foreach($this->arguments as $argument) {
			if(preg_match('~^(?:input|-i)="?(.*)"?~', $argument, $matches))
				return $matches[1];
		}
		return null;
	}
	
	/**
	 * Returns the output directory
	 *
	 * @return String The output directory as supplied from the command line
	 */
	public function getOutputDirectory() {
		foreach($this->arguments as $argument) {
			if(preg_match('~^(?:output|-o)="?(.*)"?~', $argument, $matches))
				return $matches[1];
		}
		return null;
	}
	
	/**
	 * Sets a variable in the registry
	 *
	 * @param String $name
	 * @param mixed $value
	 */
	public function set($name, $value = null) {
		$this->variables[$name] = $value;
	}
	
	
	/**
	 * Returns the variable value from the registry
	 * 
	 * If the variable doesn't exist, it returns the value of $default.
	 * 
	 * @return mixed
	 */
	public function get($name, $default = null) {
		if($this->has($name))
			return $this->variables[$name];
		else
			return $default;
	}
	
	
	/**
	 * Returns the existence of the variable in the registry
	 *
	 * @param String $name
	 * @return unknown
	 */
	public function has($name) {
		return isset($this->variables[$name]);
	}
	
}